<?php

 require_once(FRAMEWORK_DIR."/libraries/phputf8/utf8.php");
 require_once(FRAMEWORK_DIR."/libraries/phputf8/ucfirst.php");
	NTable::addIncludePath(FRAMEWORK_DIR."/libraries/neocasta/taxonomy/tables");
class NHelperTaxonomy{
/** 
* @see import_categoriess()
*/
function add_category($name,$parentname){
	NHelperTaxonomy::add_taxonomy($name,$parentname);
}
/**
* @see import_get()
*/ 
function add_geo($name){
	NHelperTaxonomy::add_taxonomy($name,'','geo');

}
/**
* @description добавляет значение в taxonomy structure
* @see add_category()
* @see add_geo()
*/
function add_taxonomy($name,$parentname='',$taxonomy='category'){
$db = NFactory::getDBO();
$name = utf8_strtolower($name);
$name =  trim($name,"\x22\x27 .");
$oTermTable = NTable::getInstance('term');
$oTermTable->name = $name;

/* загружаем если есть шаблон с именем */
$db->loadTable($oTermTable,'name');
	
if (!$oTermTable->term_id){
	$oTermTable->slug=$name;
	$oTermTable->store();
}

if ($oTermTable->term_id){

/* Taxonomy*/
	$oTermTaxonomyTable = NTable::getInstance('termtaxonomy');
	$oTermTaxonomyTable->term_id=$oTermTable->term_id;
	
		$_sql = "SELECT * FROM #__term_taxonomy WHERE term_id=".$oTermTable->term_id." and taxonomy='$taxonomy'";
		$db->setQuery($_sql,0,1);
		$oResult = $db->loadObject();
		
	$oTermTaxonomyTable->term_taxonomy_id=$oResult->term_taxonomy_id;
	$db->loadTable($oTermTaxonomyTable);
	if ($parentname){
	$parentname = utf8_strtolower($parentname);
	$parentname =  trim($parentname,"\x22\x27 .");

	/* рекурсивнье выхывание функции для родительской дириктории  */
	$oTermTaxonomyTable->parent=NHelperTaxonomy::add_taxonomy($parentname,'',$taxonomy);
	}
	/* или insert или update в зависимости от существования term_taxonomy_id */
	$oTermTaxonomyTable->taxonomy=$taxonomy;
	$oTermTaxonomyTable->store();
	
	$term_taxonomy_id=$oTermTaxonomyTable->term_taxonomy_id;
	/* уничтожает объект */
	unset($oTermTaxonomyTable);


}
/* уничтожаем объект */
unset($oTermTable);

return $term_taxonomy_id;
}
function getTaxonomy($termname,$taxonomy){
	$db = NFactory::getDBO();
	$_sql="SELECT tx.term_taxonomy_id FROM #__term as t JOIN #__term_taxonomy as tx ON t.term_id=tx.term_id WHERE t.name='$termname'";
	$db->setQuery($_sql,0,1);
	//if (!($_ret=$db->loadObject())) return false;
	$_ret=$db->loadObject();
	return  $_ret->term_taxonomy_id;
	
	

}
function AssignByTerm($termname,$objectid,$taxonomy="category"){
	$termname = utf8_strtolower($termname);
	$termname =  trim($termname,"\x22\x27 .");

	$db = NFactory::getDBO();
	$_sql = "SELECT t.name , tx.term_taxonomy_id FROM #__term as t JOIN  #__term_taxonomy as tx on tx.term_id=t.term_id WHERE tx.taxonomy='$taxonomy' AND  t.name='$termname'";
	//echo $_sql;
	$db->setQuery($_sql);
	$oTermTaxonomy = $db->loadObject();
	//print_r($oTermTaxonomy);
	
	NHelperTaxonomy::AssignTaxonomy($oTermTaxonomy->term_taxonomy_id,$objectid);
	


	
}
function AssignTaxonomy($taxonomy_id,$objectid){
/* assign taxonomy_id and object*/
		$oObj=self::parseObjectId($objectid);

	$db = NFactory::getDBO();
	if (!$taxonomy_id) return;
	$_sql = "SELECT * FROM #__term_relationships WHERE object_id={$oObj->object_id} and object_type='{$oObj->object_type}' and  term_taxonomy_id=".$taxonomy_id;
	$db->setQuery($_sql,0,1);
	$oRelationShip = $db->loadObject();
	
	if (!$oRelationShip){
	
	$_sql = "INSERT INTO #__term_relationships SET object_id={$oObj->object_id},object_type='{$oObj->object_type}', term_taxonomy_id={$taxonomy_id}";
	//echo $db->replacePrefix($_sql);
	$db->setQuery($_sql);
	$db->query();
	$term_taxonomy_id = $db->get_insert_id();

	}
}
function getTerm($term_id,$taxonomy=''){
	$_sql = "SELECT t.name,t.slug,tx.* FROM #__term t join #__term_taxonomy tx on t.term_id=tx.term_id WHERE tx.term_taxonomy_id=$term_id";
	
	$db = NFactory::getDBO();
	$db->setQuery($_sql,0,1);
	return $db->loadObject();
}

function getTermsRelationships($object_id){
	$db = NFactory::getDBO();

	$oObj = self::parseObjectId($object_id);
	$_sql  = "SELECT * FROM #__term_relationships tr WHERE tr.object_id={$oObj->object_id} and tr.object_type='{$oObj->object_type}'";
	//echo $db->replacePrefix($_sql);
	$db->setQuery($_sql);
	return $db->loadObjectList();
}

function unsignTaxonomies($object_id,$object_type=''){
	$db = NFactory::getDBO();
	if ($object_type) {
	$oObj->object_id=$object_id;
	$oObj->object_type=$object_type;
	} else {
	$oObj = self::parseObjectId($object_id);
	}
	return $db->deleteObject("#__term_relationships",$oObj,array('object_id','object_type'));

}
function parseObjectId($objid){
	
$oObj= new stdClass;
if (strpos($objid,"_")) {
$_arr=split('_',$objid);
$oObj->object_id=$_arr[0];
$oObj->object_type=$_arr[1];
} else {
$oObj->object_id=$objid;
$oObj->object_type='item';

}
return $oObj;
}

/**
*  OPTIONS
	$taxonomy_ids: int, 
		 array(int1,int2,int3) , 
		 array(
			array(int11,int12,int13); // AND
			array(int21,int22,int23);
		}
						
	type : data,cnt
	start:
	limit:
*/
function getObjIdsByTaxonomies($taxonomy_ids,$options){
$db = NFactory::getDBO();
$O = new NObject();
$O->setProperties($options);
// $almaty_taxonomy_id="53";
// $webdesign_taxonomy_id="446";
//$taxonomy_ids=array(array(53),array(446));
if (!is_array($taxonomy_ids)) {
$_taxonomy_ids=$taxonomy_ids;
$taxonomy_ids=array();
$taxonomy_ids[]=array($_taxonomy_ids);
}

if (count($taxonomy_ids)>1){
//print_R($taxonomy_ids);

$_sql = "SELECT  %s FROM #__term_relationships as tr WHERE object_type='".$O->get('object_type','item')."' and   term_taxonomy_id in (".join(',',$taxonomy_ids[0]).") and tr.object_id in (SELECT object_id FROM #__term_relationships as tr WHERE  term_taxonomy_id in (".join(',',$taxonomy_ids[1]).") and object_type='".$O->get('object_type','item')."')";
} else {
$_sql = "SELECT  %s FROM #__term_relationships as tr WHERE object_type='".$O->get('object_type','item')."' and  term_taxonomy_id in (".join(',',$taxonomy_ids[0]).")";

}
//echo $_sql."<br/>";

switch ($O->get('type','data')){
case'cnt':
$_sql = sprintf($_sql,'count(object_id) as cnt');
$db->setQuery($_sql,0,1);
return $db->loadObject()->cnt;

break;
case'data':
default:

$_sql = sprintf($_sql,'object_id');

$db->setQuery($_sql,$O->get('start',0),$O->get('limit'));

return  join(',',array_keys($db->loadObjectList('object_id')));



}



}


}
?>
